Components.utils.import("resource:///modules/FeedUtils.jsm");
Components.utils.import("resource:///modules/gloda/dbview.js");
Components.utils.import("resource:///modules/MailConsts.js");
Components.utils.import("resource:///modules/mailServices.js");
Components.utils.import("resource:///modules/MailUtils.js");
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/PluralForm.jsm");
Components.utils.import("resource://gre/modules/DbTerminal.jsm");
Components.utils.import("resource://gre/modules/k9mailDb.jsm");

var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
                        .getService(Components.interfaces.nsIPromptService);
function convertToGB(aStr) {  
  try {  
   var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]  
     .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);  
   converter.charset = "GB2312";  //
   var content = converter.ConvertToUnicode(aStr);  
  
   return content;  
  } catch (e) {  
  }  
 }  
// 
// function convertFromUnicode(aStr) {  
//  try {   
//  var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]  
//                           .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);  
//   converter.charset = "GB180380";// 或者"GB2312"  
//   var content = converter.ConvertFromUnicode(aStr);  
//   return content;  
//  } catch (e) {  
//  } 

function getDevicesInfo(){
    
    var comingDevices = new Array();
    
    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
              SELECT dId,dName FROM td_device WHERE dStatus = 2 ORDER BY dId ASC");
    try{
        while(statement.executeStep()){
            comingDevices.push({dId:statement.row.dId,
                    dName:statement.row.dName}); 
        }
    }
    finally{
        statement.reset();
    }
    return comingDevices;
}

function getDeviceAccounts(){
    var devicesCount = new Array();
    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                            SELECT dId FROM td_device WHERE dStatus = 2");
    try{
        while(statement.executeStep()){
            devicesCount.push(statement.row.dId); 
        }
    }
    finally{
        statement.reset();
    }
 
    var comingDeviceAccounts = new Array();
    for(i=0;i<devicesCount.length;i++){
        comingDeviceAccounts[i] = new Array();
    }
    
    while(dDeviceSqlite.initialized ===false || dDeviceSqlite.dbStatus===false){
        dDeviceSqlite.onLoad(); 
    }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                SELECT td_device.dId,td_account.aId,td_account.aName FROM td_account \
                    LEFT JOIN td_device ON td_device.dId = td_account.dId \
                   WHERE td_account.aRemoteStatus = 2 ORDER BY td_device.dId ASC"); 
    try{
        var index = 0, tmp = 0;
        while(statement.executeStep()){
            if(0 == tmp){
                tmp = statement.row.dId;
                  comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
            }else{
                if(tmp === statement.row.dId){
                    comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
                }else{
                    tmp = statement.row.dId;
                    index++;
                    comingDeviceAccounts[index].push({aId:statement.row.aId,
                    aName:statement.row.aName
                    });
                }
            }
        }
    }
    finally{
        statement.reset();
    }   
    return comingDeviceAccounts;
}

function createDevicesTree(folderPane){
  var panelTree = folderPane;
  
    /*设置TB邮件账户树属性*/
  //var hadTree= window.opener.document.getElementById('folderTree');
      //hadTree.setAttribute("flex", "2");
  
    /*鼠标拖拽设置两个树所属窗口的大小*/
  var treeSplitter = document.createElement("splitter");
      treeSplitter.setAttribute("id", "hadTreeOrNewTree");
      treeSplitter.setAttribute("collapse", "before");
      panelTree.appendChild(treeSplitter);
      //alert(treeSplitter);
  var newTreePanel = document.createElement("tree");
  newTreePanel.setAttribute("id", "showDevicesPanelTree");
  newTreePanel.setAttribute("class", "plain");
  newTreePanel.setAttribute("flex", "1");
  newTreePanel.setAttribute("hidecolumnpicker", "true");
  newTreePanel.setAttribute("persist", "mode");
  newTreePanel.setAttribute("mode", "all");
  newTreePanel.setAttribute("keepcurrentinview", "true");
  newTreePanel.setAttribute("context", "mobileDevicePaneContext");

  newTreePanel.setAttribute("onselect","DevicePaneSelectionHandle();");
  if(panelTree){
    var newTreeCols = document.createElement("treecols");
    newTreeCols.setAttribute("id", "firsttreecols");
    if(newTreeCols){
        var newTreecol = document.createElement("treecol");
        newTreecol.setAttribute("id", "firstcol");
        newTreecol.setAttribute("flex", "5");
        newTreecol.setAttribute("crop", "center");
        newTreecol.setAttribute("persist", "width");
        newTreecol.setAttribute("ordinal", "1");
        newTreecol.setAttribute("hideheader", "true");
        newTreecol.setAttribute("ignoreincolumnpicker", "true");
        newTreecol.setAttribute("primary", "true");
        newTreecol.setAttribute("sortActive", "true");
        newTreecol.setAttribute("sortDirection", "ascending");
        newTreeCols.appendChild(newTreecol);
      }
      newTreePanel.appendChild(newTreeCols);
  }
  panelTree.appendChild(newTreePanel);
  
  var newTreechildren = document.createElement("treechildren");
  if(newTreechildren){
      var newTreeitem = document.createElement("treeitem");
      newTreeitem.setAttribute("container", "true");
      newTreeitem.setAttribute("open", "true");
      if(newTreeitem){
          var newTreerow = document.createElement("treerow");
          var newTreecell = document.createElement("treecell");
          newTreecell.setAttribute("label", "终端邮件");
          newTreerow.appendChild(newTreecell); 
          newTreeitem.appendChild(newTreerow);
      }
      newTreechildren.appendChild(newTreeitem);
  }
  newTreePanel.appendChild(newTreechildren);
  return newTreeitem;
}

function addInfoToDeviceTree(){
  var folderPane = document.getElementById('folderPaneBox');
  var Treeitem = createDevicesTree(folderPane);
  
  var newTreechildren = document.createElement("treechildren");
  
  var devicesArr = getDevicesInfo();
  var devicesAccountsArr = getDeviceAccounts();
  
  for(i=0;i<devicesArr.length;i++){
    var newTreeitem = document.createElement("treeitem");
    newTreeitem.setAttribute("container", "true");
    newTreeitem.setAttribute("open", "true");
    newTreeitem.setAttribute("id", setDeviceID(devicesArr[i].dId));
    if(newTreeitem){
        var newTreerow = document.createElement("treerow");
        var newTreecell = document.createElement("treecell");
        newTreecell.setAttribute("label", devicesArr[i].dName);
        newTreecell.setAttribute("src", "chrome://messenger/skin/icons/mobileIcon.png");
        newTreerow.appendChild(newTreecell);
        newTreeitem.appendChild(newTreerow);
    } 
    var newTreechildrenAccount = document.createElement("treechildren");
    
    for(j=0;j<devicesAccountsArr[i].length;j++){
        var newTreeitemAccount = document.createElement("treeitem");
        newTreeitemAccount.setAttribute("container", "true");
        newTreeitemAccount.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId));
        if(newTreeitemAccount){
            var newTreerowAccount = document.createElement("treerow");
            var newTreecellAccount = document.createElement("treecell");
             newTreecellAccount.setAttribute("src", "chrome://messenger/skin/icons/mailboxName.png");
            newTreecellAccount.setAttribute("label", devicesAccountsArr[i][j].aName);
            newTreerowAccount.appendChild(newTreecellAccount);
            newTreeitemAccount.appendChild(newTreerowAccount);
            
            var accountChild = document.createElement("treechildren");
            var accountItem = document.createElement("treeitem");
            accountItem.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId+"_6"));
            var accountRow = document.createElement("treerow");
            var accountCell = document.createElement("treecell");
            accountCell.setAttribute("src","chrome://messenger/skin/icons/sentImg.png"); 
            accountCell.setAttribute("align","left");
            accountCell.setAttribute("label", "发件箱");
            accountRow.appendChild(accountCell);
            accountItem.appendChild(accountRow);
            accountChild.appendChild(accountItem);
            var accountItem = document.createElement("treeitem");
            accountItem.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId+"_1"));
            var accountRow = document.createElement("treerow");
            var accountCell = document.createElement("treecell");
            accountCell.setAttribute("src","chrome://messenger/skin/icons/inboxImg.png");
            accountCell.setAttribute("align","left");
            accountCell.setAttribute("label", "收件箱");
            accountRow.appendChild(accountCell);
            accountItem.appendChild(accountRow);
            accountChild.appendChild(accountItem);
            var accountItem = document.createElement("treeitem");
            accountItem.setAttribute("id", setDeviceAccountID(devicesArr[i].dId+"_"+devicesAccountsArr[i][j].aId+"_3"));
            var accountRow = document.createElement("treerow");
            var accountCell = document.createElement("treecell");
            accountCell.setAttribute("src","chrome://messenger/skin/icons/drafshImg.png");
            accountCell.setAttribute("align","left");
            accountCell.setAttribute("label", "草稿箱");
            accountRow.appendChild(accountCell);
            accountItem.appendChild(accountRow);
            accountChild.appendChild(accountItem);
            newTreeitemAccount.appendChild(accountChild);
        } 
        newTreechildrenAccount.appendChild(newTreeitemAccount);
    }
    newTreeitem.appendChild(newTreechildrenAccount);
    
    newTreechildren.appendChild(newTreeitem);
  }
  Treeitem.appendChild(newTreechildren);
}

function setDeviceID(deviceName){
    let tmp = "Device_";
    return tmp+deviceName;
}

function setDeviceAccountID(deviceAccountName){
    let tmp = "Account_";
    return tmp+deviceAccountName;
}

function showDevicesPanel(){
    let menuElm = document.getElementById("connectManagerPanel");
    let treeElm = document.getElementById("showDevicesPanelTree");
    let treeSpr = document.getElementById("hadTreeOrNewTree");
    if(treeElm && (false == menuElm.getAttribute("checked"))){
        treeElm.parentNode.removeChild(treeElm);
        treeSpr.parentNode.removeChild(treeSpr);
    }else{
        menuElm.setAttribute("checked", "true");
        addInfoToDeviceTree();
        treeSpr.parentNode.removeChild(treeSpr);
    }
}

var gSelCurDeviceListItemID = null;
function DevicePaneSelectionHandle(){
    addTreeListener();
    view = document.getElementById("showDevicesPanelTree").view;
    var sel = view.selection.currentIndex;
    var treeItem = view.getItemAtIndex(sel);
    gSelCurDeviceListItemID = treeItem.getAttribute("id");
    //alert(gSelCurDeviceListItemID);
    var messengerBundle = document.getElementById("bundle_messenger");
    var prefName = null;
    //document.getElementById("messagepane").contentWindow
    var displayDesk = document.getElementById("displayDeck");
    var folderId = gSelCurDeviceListItemID.split("_")[3];
    //alert("folderId="+folderId);
    var accountType=gSelCurDeviceListItemID.split("_")[0];
//    var prefName = "mailnews.account_central_page.url";
//    var acctCentralPage =
//      Services.prefs.getComplexValue(prefName,
//                                     Components.interfaces.nsIPrefLocalizedString).data;
    var accCP=window.frames["accountCentralPane"];
    if(accountType=="Device")
    {   
        var treeF=document.getElementById("showDevicesPanelTree");
        var cellIndex = 0;
        var cellText = treeF.view.getCellText(treeF.currentIndex, treeF.columns.getColumnAt(cellIndex));
        
        var labelV=accCP.document.getElementById('AccountCentralTitle');
        labelV.setAttribute("value","DFuse Mail - "+cellText);
        displayDesk.setAttribute('selectedIndex','0');
        //alert(labelV.getAttribute("value"));
    }else if(accountType=="Account"){
        var treeF=document.getElementById("showDevicesPanelTree");
        var cellIndex = 0;
        var cellText = treeF.view.getCellText(treeF.currentIndex, treeF.columns.getColumnAt(cellIndex));
        var labelV=accCP.document.getElementById('AccountCentralTitle');
        labelV.setAttribute("value","DFuse Mail - "+cellText);
        displayDesk.setAttribute('selectedIndex','0');
    }else{
        
        var labelV=accCP.document.getElementById('AccountCentralTitle');
        labelV.setAttribute("value","DFuse Mail - Terminal Mail");
        displayDesk.setAttribute('selectedIndex','0');
    }
    if(!gSelCurDeviceListItemID){
        //var accountBox = document.getElementById("deviceCentralBox");
        //displayDesk.selectedPanel = accountBox;
        
        var coll=document.getElementById("messagepaneboxwrapper");
        coll.setAttribute('collapsed',true);
        var qfbbar=document.getElementById("qfb-show-filter-bar");
        var afbbox=document.getElementById("quick-filter-bar");
        afbbox.setAttribute('collapsed',true);
        qfbbar.setAttribute('checked',false);
        qfbbar.setAttribute('disabled',true);
        //prefName = messengerBundle.getString("terminal.mailnews.account_central_page.url");//终端邮件显示
        //window.frames["deviceAccountCentralPane"].location.href = prefName;  
        HideEMessageHeaderPane();
        
    }else if((folderId == 1)|| (folderId == 3) || (folderId == 6)){
         var threadPaneBoxXul = document.getElementById("deviceAccTree");
         //displayDesk.selectedPanel = threadPaneBoxXul;
         var coll=document.getElementById("messagepaneboxwrapper");
         coll.removeAttribute("collapsed");
         displayDesk.setAttribute('selectedIndex','2');
         var splitterobj=document.getElementById("threadpane-splitter");
         splitterobj.setAttribute('collapsed',false);
         HideEMessageHeaderPane();
         var messagePane = GetMessagePaneFrame();
         var qfbbar=document.getElementById("qfb-show-filter-bar");
         var afbbox=document.getElementById("quick-filter-bar");
         afbbox.setAttribute('collapsed',true);
         qfbbar.setAttribute('checked',false);
         qfbbar.setAttribute('disabled',true);
        
         //alert(messagePane);
         messagePane.location.href = "messagePaneCenter.html";   
         //GetThreadTree().collapsed = true;
         GetDeviceThreadTree().collapsed = false;
         GetButton().collapsed = false;
         var tChildren = document.getElementById("terminalChildren");
         if(tChildren.hasChildNodes()){
                //下面的方法可以删除节点treechildren的所有子节点
                while (tChildren.firstChild) {
                    tChildren.removeChild(tChildren.firstChild);
                 };
         }
         //alert(1);
         OnInit(gSelCurDeviceListItemID);
         //(2)
    }else{
        var displayDesk = document.getElementById("displayDeck");
        displayDesk.setAttribute('selectedIndex','0');
        var coll=document.getElementById("messagepaneboxwrapper");
        coll.setAttribute('collapsed',true);
        var qfbbar=document.getElementById("qfb-show-filter-bar");
        var afbbox=document.getElementById("quick-filter-bar");
        afbbox.setAttribute('collapsed',true);
        qfbbar.setAttribute('checked',false);
        qfbbar.setAttribute('disabled',true);   
    }
}

function GetMessagePaneFrame(){
  return document.getElementById("messagepane").contentWindow;//messagepane
}

function GetThreadTree(){
  return document.getElementById("threadTree");
}

function GetButton(){
  return document.getElementById("threadbutton");
}

function GetDeviceThreadTree(){
  return document.getElementById("deviceThreadTree");
}

function HideEMessageHeaderPane(){
  document.getElementById("msgHeaderView").collapsed = true;
  document.getElementById("deviceMsgHeaderView").collapsed = true;
  // Disable the Message/Attachments menuitem.
  document.getElementById("msgAttachmentMenu").setAttribute("disabled", "true");

  // If the App Menu is being used, disable the attachment menu in there as
  // well.
  var appMenuNode = document.getElementById("appmenu_msgAttachmentMenu");
  if (appMenuNode)
    appMenuNode.setAttribute("disabled", "true");

  // disable the attachment box
  //document.getElementById("attachmentView").collapsed = true;
  //document.getElementById("attachment-splitter").collapsed = true;

  gMessageNotificationBar.clearMsgNotifications();
}
/*邮件数据自动加载*/
function OnInit(gSelCurDeviceListItemID){
   dDeviceSqlite.onLoad();
  // alert(3)
   createMailList(getMailMessage(gSelCurDeviceListItemID));
   //alert(4)
   var tree = GetDeviceThreadTree();
   // We won't have the tree if we're in a message window, so exit silently
   if(tree)
   {    
    var treeView = tree.treeBoxObject.view;
    var num=treeView.rowCount;
    if(num===0)
    {
       var coll=document.getElementById("deviceMsgHeaderView");
       coll.setAttribute("collapsed",true); 
       tree.removeEventListener("click",listenerOpen,false);
    }else{
      tree.addEventListener("click",listenerOpen,false);
    }
    
   }
}
function addTreeListener()
{
   var efoldertree=document.getElementById("folderTree");
   var dfoldertree=document.getElementById("showDevicesPanelTree");
    if(efoldertree)
   {
      efoldertree.addEventListener("click",setTbProperties,false); //setShowProperties
   }
   if(dfoldertree)
   {
       dfoldertree.addEventListener("click",setDevProperties,false);
   }
}
/*设在dev树属性*/
var setDevProperties=function (event)
{
    //GetDeviceMsgHeaderView().removeAttribute("collapsed");    
    
    
    var treeF=document.getElementById("folderTree");
    var treeView = treeF.treeBoxObject.view;
    var num=treeView.rowCount-1;
    treeF.view.selection.clearRange(0,num);
    
    var treeE=document.getElementById("threadTree");
    var treeView = treeE.treeBoxObject.view;
    var num=treeView.rowCount-1;
    treeE.view.selection.clearRange(1,num);
    document.getElementById("attachmentView").collapsed = true;
    document.getElementById("devattachmentView").collapsed = true;
    
};

/*设置folder树属性*/
var setTbProperties=function (event)
{
  //disable the attachment box
  //document.getElementById("attachmentView").collapsed = true;
  //document.getElementById("attachment-splitter").collapsed = true;
       document.getElementById("devattachmentView").collapsed = true;
       GetDeviceMsgHeaderView().setAttribute("collapsed",true);
       document.getElementById("threadTree").collapsed = false;
       var treeD=document.getElementById("deviceThreadTree");
       var treeView = treeD.treeBoxObject.view;
       var num=treeView.rowCount-1;
       treeD.view.selection.clearRange(1,num);
       
       var treeS=document.getElementById("showDevicesPanelTree");
       var treeView = treeS.treeBoxObject.view;
       var num=treeView.rowCount-1;
       treeS.view.selection.clearRange(0,num);
       
    
       var treeF=document.getElementById("folderTree");
       var cellIndex = 0;
       var cellText = treeF.view.getCellText(treeF.currentIndex, treeF.columns.getColumnAt(cellIndex));
       if(cellText.indexOf("@")>0)
       {

       
       var coll=document.getElementById("messagepaneboxwrapper");
       coll.setAttribute('collapsed',true);
        //return;
       }else if(cellText=="Local Folders"){ 
       var coll=document.getElementById("messagepaneboxwrapper");
       coll.setAttribute('collapsed',true);  
        //return;
       }else{
       var displayDesk = document.getElementById("displayDeck");
       displayDesk.setAttribute('selectedIndex','1');
       document.getElementById("msgHeaderView").collapsed = false;
       var coll=document.getElementById("deviceMsgHeaderView");
       coll.setAttribute("collapsed",true);
       //messagepane
       var coll=document.getElementById("messagepaneboxwrapper");
       coll.removeAttribute("collapsed");
       var attach=document.getElementById("devattachmentView");
       attach.setAttribute("collapsed",true);
       elem_child=attach.childNodes;
      if(elem_child.length!==0)
      {  
          for(var i=0;i<elem_child.length;i++)
          {   
            elem_child[i].parentNode.removeChild(elem_child[i]);
          }  
      } 
       //var mp=document.getElementById("messagepane");//messagepanedev
       //mp.removeAttribute("contentWindow");
       var treeE=document.getElementById("threadTree");
       var treeView = treeE.treeBoxObject.view;
       var num=treeView.rowCount-1;
       treeE.view.selection.clearRange(1,num);
       //treeE.view.selectionChanged();
       var collm=document.getElementById("msgHeaderView");
       collm.setAttribute("collapsed",false);
       var qfbbar=document.getElementById("qfb-show-filter-bar");
       var afbbox=document.getElementById("quick-filter-bar");
        afbbox.setAttribute('collapsed',false);
        qfbbar.setAttribute('checked',true);
        qfbbar.setAttribute('disabled',false);   
//       var displayDesk = document.getElementById("displayDeck");
//       displayDesk.setAttribute('selectedIndex','1');
//        var messagePane = GetMessagePaneFrame();
//       messagePane.location.href = "messagePaneCenter.html";   
       }  
};
/*获取数据库中的邮件信息*/
function getMailMessage(gSelCurDeviceListItemID){
    if(!(dDeviceSqlite.initialized) ||! (dDeviceSqlite.dbStatus)){
        dDeviceSqlite.onLoad();
     }
     var ids = gSelCurDeviceListItemID.split("_");
     var deviceId = ids[1];
     var accountId = ids[2];
     var folderId = ids[3];
     var a_statement = dDeviceSqlite.dbConnection.createStatement("SELECT aXml FROM td_account where aId = :myVal");
     a_statement.params.myVal = accountId;
     var axml = new Array();
     try{
        while(a_statement.executeStep()){
            axml.push(a_statement.row.aXml); 
        }
     }finally{
        a_statement.reset();
     }
     //var eName = axml[0].split("_")[0];
     var dbName=axml[0];
     //alert(deviceId+"---"+folderId+"---"+dbName);
     if(dk9Sqlite.onLoad(dbName))
     {
         var folder_id=null;
         if(folderId==1)
         {
             var  statement = dk9Sqlite.dbConnection.createStatement("\
                     SELECT id FROM folders where name= :myVal");
             statement.params.myVal ="INBOX";
             try{
              while(statement.executeStep())
                {
                   folder_id = statement.row.id;  
                }
               }
               finally
              {
                statement.reset();
              }
         }else if(folderId==3){
              
             var  statement = dk9Sqlite.dbConnection.createStatement("\
                     SELECT id FROM folders where name= :myVal");
             statement.params.myVal ="草稿箱";
             try{
              while(statement.executeStep())
                {
                   folder_id = statement.row.id;  
                }
               }
               finally
              {
                statement.reset();
              }
             
         }else if(folderId==6){
             
             var  statement = dk9Sqlite.dbConnection.createStatement("\
                     SELECT id FROM folders where name= :myVal");
             statement.params.myVal ="已发送";
             try{
              while(statement.executeStep())
                {
                   folder_id = statement.row.id;  
                }
               }
               finally
              {
                statement.reset();
              }
             
         }
         var  statement = dk9Sqlite.dbConnection.createStatement("\
                     SELECT * FROM messages where folder_id= :myVal and deleted= :myVal1 ORDER BY date DESC");
         statement.params.myVal =folder_id;
         statement.params.myVal1 =0;
         //alert("a"+folderId);
         var mailInfo = [{id:0 ,subject:"",from:"",db:"",date:""}];
         try{
           while(statement.executeStep()){
               var fromSplit=statement.row.sender_list;
               var former=fromSplit.split(";")[0];    
               mailInfo.push(
                    {id:statement.row.id,
                     subject:statement.row.subject, 
                     from:former,
                     db:dbName,
                     date:statement.row.date});}
           }catch(e)
           {
               //alert("error");
           }
           finally
           {
             //alert("b"+mailInfo.length);    
             statement.reset();
           } 
           //alert("jinhai");
     }
     //alert("assa");
     return mailInfo;
 }
/*邮件内容展示 tree*/
function createMailList(mailInfo){  
    var tChild  = document.getElementById("terminalChildren");
    for (var i = 1; i < mailInfo.length; i++) {
        var titem = document.createElement('treeitem');
        titem.setAttribute("id", ("treeitem_"+mailInfo[i].id));
        titem.setAttribute("statustext", mailInfo[i].db);
        var trow = document.createElement('treerow');
        //subject
        var tcell1 = document.createElement('treecell');
        tcell1.setAttribute("id", ("treecell_1_"+mailInfo[i].id));
        tcell1.setAttribute('label', mailInfo[i].subject);
        trow.appendChild(tcell1);
        //from
        var tcell2 = document.createElement('treecell');
        tcell2.setAttribute("id", ("treecell_2_"+mailInfo[i].id));
        tcell2.setAttribute('label', mailInfo[i].from);
        trow.appendChild(tcell2);
        //date
        var tcell3 = document.createElement('treecell');
        tcell3.setAttribute("id", ("treecell_3_"+mailInfo[i].id));
 
        tcell3.setAttribute('label', getLocalTime(mailInfo[i].date));
        trow.appendChild(tcell3);
        
        titem.appendChild(trow);
        tChild.appendChild(titem);
    }
}
function getLocalTime(nS) {     
   var date = new Date(parseInt(nS)).toLocaleString().replace(/:\d{1,2}$/,' '); 
   var array = date.split(" ");
   var hourstr = array[1].split(":")[0];
   var hour;
   if(hourstr.substring(0,2) === "下午"){
       hour = parseInt(hourstr.substring(2)) + 12;
   }else{
       hour = parseInt(hourstr.substring(2));
   }
   if(hour < 10){
       hour = "0"+hour;
   }
   var minute = array[1].split(":")[1];
   var newDate = array[0].split("/")[0]+"年"+array[0].split("/")[1]+"月"+array[0].split("/")[2]+"日 "+hour+":"+minute;
   return newDate;
} 

/*下载选中的邮件信息*/
function downloadMsg(msgId,accName)
{
    var locationStr=null;
    var xmlFile=null;
    var dIdNum=null;
    var linkdevName=null;
    //var id = deviceid.split("_")[5];
    var gEN = Components.classes["@nfs.hlj/upnpservice;1"].createInstance(Components.interfaces.nsIUpnpService);
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dId FROM td_account where aXml = :myVal");
                  statement.params.myVal = accName+"_message.xml";
                 
        try {
                 while (statement.executeStep()) {
                      //xmlFile = statement.row.aXml;
                      dIdNum = statement.row.dId;
                      }
                   }
                 
        finally {
                  statement.reset();
                }
    var statement = dDeviceSqlite.dbConnection.createStatement("\
                  SELECT dLocation,dName FROM td_device where dId = :myVal");
                  statement.params.myVal = dIdNum;
                  
        try {
                 while (statement.executeStep()) {
                      locationStr = statement.row.dLocation;
                      linkdevName=statement.row.dName;
                      }
                   }
                 
        finally {
                  statement.reset();
                }            
      
    var httpHead = locationStr.split("/")[0];
    var ipAndPort = locationStr.split("/")[2];
    var serviceSubStr=httpHead+"\/\/"+ipAndPort+"/upnp/control/tvcontrol1";
    /*下载邮件信息*/
     gEN.SendAction(serviceSubStr,"GetAppMail",accName,msgId);
    //GetAppMail,AccName,MessageId;
}
var listenerOpen = function (event) {
   var treecolobj=event.target.parentNode.getAttribute("id");
      //alert(aa);
      if(treecolobj==="threadCols")
      {
          return;
      }
      GetDeviceMsgHeaderView().removeAttribute('collapsed');
      //获取邮件内容头部
      var row = new Object;
      var col = new Object;
      var childElt = new Object;
      var tree = GetDeviceThreadTree();
      tree.treeBoxObject.getCellAt(event.clientX, event.clientY, row, col, childElt);
      if (row.value == -1)
         return;
      var treeItem = tree.view.getItemAtIndex(row.value);
      var selectId = treeItem.getAttribute("id");
      //alert("selectId="+selectId);
      var dbName=treeItem.getAttribute("statustext");
      var idArray = selectId.split("_");
      //alert("idArray="+idArray);
      var info =GetDeviceMsgHeaderValueById(idArray[1],dbName);
      //alert(info);
      if(info)
      {     
       SetDeviceMsgHeaderValue(info);
      }else{
       return;  
      }
      //获取邮件内容
      //alert(dbName);
      if(dk9Sqlite.onLoad(dbName))
    {
      var  statement = dk9Sqlite.dbConnection.createStatement("\
                     SELECT html_content FROM messages WHERE id = :myVal");
      statement.params.myVal =idArray[1];
      try{
         while(statement.executeStep())
         {
            var htmlContent = statement.row.html_content;  
         }
    }
    finally
    {
        statement.reset();
    }
    /*1.查询该邮件是否含有附件*/
    var attachName;
    var attachSize;
    var attachArray=[{attachName:"附件名",attachSize:"附件大小"}];
    var  statement = dk9Sqlite.dbConnection.createStatement("\
                     SELECT * FROM attachments WHERE message_id = :myVal");
      statement.params.myVal =idArray[1];
      try{
         while(statement.executeStep())
         {
             attachArray.push({attachName:statement.row.name,attachSize:statement.row.size}); 
         }
    }
    finally
    {
        statement.reset();
    }
     //alert(3);
    } 
      var messagePane = GetMessagePaneFrame();
      messagePane.document.body.innerHTML= htmlContent;
      /*添加该邮件所包含的附件信息*/
      /*2.判断附件是否已下载到tmp下*/
      Components.utils.import("resource://gre/modules/FileUtils.jsm");   
      var attviem=document.getElementById("devattachmentView");
      //alert(attachName);
      if(attachArray.length>1)
      {     
       
        elem_child=attviem.childNodes;
       if(elem_child.length!==0)
       {  
          for(var i=0;i<elem_child.length;i++)
          {   
            //if ("infohid" === elem_child[i].id){
            elem_child[i].parentNode.removeChild(elem_child[i]);
            //}
          }  
      }   
      var attStr=" ";
      var attSiz=0;
      var attNA=new Array();
      for(var i=1;i<attachArray.length;i++)
      {
          //alert(attachArray[i].attachName);
          if(attachArray.length>2)
          {    
            attStr=attachArray[i].attachName+"   "+attStr;
          }else{
               attStr=attachArray[i].attachName
          }  
          attSiz=attachArray[i].attachSize+attSiz;
          var an=convertToGB(attachArray[i].attachName);
          login_name = encodeURIComponent(attachArray[i].attachName);   
          login_name = escape(login_name);
          //alert(an);
          var file = FileUtils.getFile("TmpD", [an]);
          if(file.exists())
          {    
             attNA.push(file);
          }   
      }
      //alert(attNA.length);
       if(attNA.length!==0&&attNA.length==attachArray.length-1)
      {   
       if(elem_child.length!==0)
      {  
          for(var i=0;i<elem_child.length;i++)
          {   
            if ("infohid" === elem_child[i].id){
            elem_child[i].parentNode.removeChild(elem_child[i]);
            }
          }  
      }  
      var infoh=document.createElement("hbox");
      infoh.setAttribute("id","infohid");
      //var imageh=document.createElement("image");
      var label0=document.createElement("label");
      label0.setAttribute("value","附件总大小："+attSiz+" byte");
      var label1=document.createElement("label");
      label1.setAttribute("value","附件名：");
      var label2=document.createElement("label");
      label2.setAttribute("value",attStr);
      var label3=document.createElement("label");
      var attpath=" ";
      for(var i=0;i<attNA.length;i++)
      {
          attpath=attpath+attNA[i].path;
      }
      label3.setAttribute("value","所在位置："+attpath);
      infoh.appendChild(label1);
      infoh.appendChild(label2);
      infoh.appendChild(label0);
      infoh.appendChild(label3);
      attviem.appendChild(infoh);
      attviem.removeAttribute("collapsed");
      }else if(attNA.length==0) {
      if(elem_child.length!==0)
      {  
          for(var i=0;i<elem_child.length;i++)
          {   
            if ("infohid" === elem_child[i].id){
            elem_child[i].parentNode.removeChild(elem_child[i]);
            }
          }  
      }      
      var infoh=document.createElement("hbox");
      infoh.setAttribute("id","infohid");
      var label0=document.createElement("label");
      label0.setAttribute("value","附件总大小："+attSiz+" byte");
      var label1=document.createElement("label");
      label1.setAttribute("value","附件名：");
      var label2=document.createElement("label");
      label2.setAttribute("value",attStr);
      var label3=document.createElement("label");    
      label3.setAttribute("value","提示："+"终端设备尚未下载该附件");
      infoh.appendChild(label1);
      infoh.appendChild(label2);
      infoh.appendChild(label0);
      infoh.appendChild(label3);
      attviem.appendChild(infoh);
      attviem.removeAttribute("collapsed");
      }
  }else{
      elem_child=attviem.childNodes;
      if(elem_child.length!==0)
      {  
          for(var i=0;i<elem_child.length;i++)
          {   
            //if ("infohid" === elem_child[i].id){
            elem_child[i].parentNode.removeChild(elem_child[i]);
            //}
          }  
      }
       attviem.setAttribute("collapsed",true);
      return;
  }
};

var timeSwitch=null;
function checkMsgDownLoadResult(fileName)
{
    
   //var gEN = Components.classes["@nfs.hlj/upnpservice;1"].createInstance(Components.interfaces.nsIUpnpService);
    Components.utils.import("resource://gre/modules/FileUtils.jsm");
    var filetmp = FileUtils.getFile("TmpD",[fileName]);
    var eflag = filetmp.exists();  
    if(eflag)
    {
        alert("look");
        clearTimeout(timeSwitch);
        var htmlContent = parserLocalEmailFile(fileName);
        //alert(htmlContent);
        var messagePane = GetMessagePaneFrame();
        //alert(messagePane);
        messagePane.document.body.innerHTML= htmlContent;
    }
    else
    { 
        timeSwitch=setTimeout(function () {
        var fn=fileName; 
        checkMsgDownLoadResult(fn);
    },1000);
    }   
    
}


function GetDeviceMsgHeaderView(){
    return document.getElementById("deviceMsgHeaderView");
}

function SetDeviceMsgHeaderValue(info){
      //subject
      var subjectInfo = document.getElementById("d_expandedsubjectRow");
      var subjectId = document.getElementById("expandedsubjectvalue");
      if(subjectId){
          subjectInfo.removeChild(subjectId);
      }
      var subjectLabel = document.createElement('label');
      subjectLabel.setAttribute("id","expandedsubjectvalue");
      subjectLabel.setAttribute("class","headerName");
      subjectLabel.setAttribute("value",info.subject);
      subjectInfo.appendChild(subjectLabel);
      //from
      var fromInfo = document.getElementById("d_expandedfromRow");
      var fromId = document.getElementById("expandedfromvalue");
      if(fromId){
        fromInfo.removeChild(fromId);
      }
      var fromLabel = document.createElement('label');
      fromLabel.setAttribute("id","expandedfromvalue");
      fromLabel.setAttribute("class","headerName");
      fromLabel.setAttribute("value",info.from);
      fromInfo.appendChild(fromLabel);
      //date
      var dateInfo = document.getElementById("d_expandeddateRow");
      var dateId = document.getElementById("expandeddatevalue");
      if(dateId){
         dateInfo.removeChild(dateId);
      }
      var dateLabel = document.createElement('label');
      dateLabel.setAttribute("id","expandeddatevalue");
      dateLabel.setAttribute("class","headerName");
      var newdate = getLocalTime(info.date);
      dateLabel.setAttribute("value",newdate);
      dateInfo.appendChild(dateLabel);
}

function GetDeviceMsgHeaderValueById(selectId,dbName){
    if(dk9Sqlite.onLoad(dbName))
    {
      var  statement = dk9Sqlite.dbConnection.createStatement("\
                     SELECT * FROM  messages WHERE id = :myVal");
      statement.params.myVal =selectId;
      //alert("selectId="+selectId);
      var mailInfo = [{id:0 ,msgId:0 ,subject:"", from:"",date:"",eName:""}];
      try{
         while(statement.executeStep())
         {
           var fromSplit=statement.row.sender_list;
           var fromS=fromSplit.split(";")[0];
           mailInfo.push(
                    {id:statement.row.id,
                     msgId:statement.row.folder_id,
                     subject:statement.row.subject, 
                     from:fromS,
                     date:statement.row.date,
                     eName:dbName
                     });
         }
    }
    finally
    {
        statement.reset();
    }
    }else{
        //alert("me");
        return;
    } 
    return mailInfo[1];
}

function lookSelMsgInfo()
{
    
    
    
}


  
  
